package com.axzhengxin.platform.common.util;

import com.ruoyi.common.core.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author AHZJ0005
 * redis工具
 */
@Slf4j
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 使用redis加锁，保护抢单功能
     *
     * @param key
     * @return
     */
    public boolean getLock(String key) {
        try {
            Long count = redisTemplate.opsForValue().increment(key, 1);
            if (count == 1) {
                redisTemplate.expire(key, 3, TimeUnit.SECONDS);
                return true;
            } else {
                Long time = redisTemplate.getExpire(key);
                if (time == -1) {
                    redisTemplate.expire(key, 3, TimeUnit.SECONDS);
                    return true;
                }
            }
            //大于一则存在
            return false;
        } catch (Exception e) {
            log.info("redis加锁失败！");
            redisTemplate.delete(key);
            return true;
        }
    }

    /**
     * 释放锁
     *
     * @param key
     * @return
     */
    public void disableLock(String key) {
        try {
            redisTemplate.delete(key);
        } catch (Exception e) {
            log.info("redis释放锁失败！");
        }
    }



}
